Referring to a Type with typeof

Contents|Index|Previous|Next
Referring to a type with `typeof`

Another way to refer to the type of an expression is with typeof. The syntax of using of this keyword looks like sizeof, but the construct acts semantically like a type name defined with typedef.

There are two ways of writing the argument to typeof: with an expression, or with a type. The following is an example with an expression.

    typeof (x[0](1))

This input assumes that x is an array of functions; the type described is that of the values of the functions. The following is an example with a type name as the argument.

    typeof (int *)

If you are writing a header file that must work when included in ANSI C programs, write __typeof__ instead of typeof. See Alternate keywords. A typeof-construct can be used anywhere a typedef name could be used. For example, you can use it in a declaration, in a cast, or inside of sizeof or typeof. In the following, the type described is that of pointers to int.

    typeof (*x) y;

- The following declaration uses y as an array of such values.

    typeof (*x) y[4];

- The following declaration uses y as an array of pointers to characters.

    typeof (typeof (char *)[4]) y;

It is equivalent to the traditional C declaration, char *y[4];.

To see the meaning of the declaration using typeof, and why it might be a useful way to write, lets rewrite it with the following macros.

    #define pointer(T) typeof(T *)
    #define array(T, N) typeof(T [N])

Now the declaration can be rewritten the following way.

    array (pointer (char), 4) y;

Thus, array (pointer (char), 4) is the type of arrays of 4 pointers to char.

Top|Contents|Index|Previous|Next